package cn.janus.component;

import cn.janus.pojo.entity.Bill;
import cn.janus.service.IBillService;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@AllArgsConstructor
public class DataPreheatingComponent {
    private final RedisTemplate<String, Bill> redisTemplate;
    private final IBillService iBillService;

    @PostConstruct
    @Scheduled(cron = "0 */10 * * * *")
    public void preheatingData() {
        List<Bill> bills = iBillService.list();
        bills = bills.stream().sorted(Comparator.comparing(Bill::getTime)).collect(Collectors.toList());
        long expireTimeInSeconds = 11; // 过期时间为1小时，可以根据需要调整
        ListOperations<String, Bill> listOperations = redisTemplate.opsForList();
        listOperations.trim("bills", 0, -1);
        listOperations.rightPushAll("bills", bills);
        redisTemplate.expire("bills", expireTimeInSeconds, TimeUnit.MINUTES);
    }
}
